package com.sc.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class EntityHandler implements MetaObjectHandler {

    //todo 从登陆信息里取登陆id
    String UserId = "1";
    @Override
    public void insertFill(MetaObject metaObject) {
        if (this.existField(metaObject, "createBy")) {
            this.setFieldValByName("createBy", UserId,metaObject);
        }

        if (this.existField(metaObject, "createTime")) {
            this.setFieldValByName("createTime", new Date(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (this.existField(metaObject, "updateBy")) {
            this.setFieldValByName("updateBy", UserId, metaObject);
        }

        if (this.existField(metaObject, "updateTime")) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

    private boolean existField(MetaObject metaObject, String fieldName) {
        return metaObject.hasSetter(fieldName);
    }
}
